package com.qny.ai.service.impl;

import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;
import com.qny.ai.config.KodoConfig;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.Base64;

@Service
@RequiredArgsConstructor
public class KodoStorageService {

    private final KodoConfig cfg;

    private Region regionFromCode(String code) {
        if (code == null) return Region.autoRegion();
        // 简化：默认自动区域，或根据常用标识切换
        return Region.autoRegion();
    }

    public String uploadBytes(byte[] data, String ext) throws Exception {
        Configuration configuration = new Configuration(regionFromCode(cfg.getRegion()));
        UploadManager uploadManager = new UploadManager(configuration);
        Auth auth = Auth.create(cfg.getAccessKey(), cfg.getSecretKey());
        String upToken = auth.uploadToken(cfg.getBucket());
        String key = "audio/" + java.time.LocalDate.now() + "/" + UUID.randomUUID() + (ext != null ? ("." + ext) : "");
        Response res = uploadManager.put(data, key, upToken);
        if (!res.isOK()) {
            throw new RuntimeException("kodo upload failed: " + res.toString());
        }
        String domain = cfg.getPublicDomain();
        if (domain == null || domain.isEmpty()) {
            throw new RuntimeException("publicDomain not configured");
        }
        // 若未带协议，默认使用 http://（一些测试域名不支持 https）
        if (!domain.startsWith("http://") && !domain.startsWith("https://")) {
            domain = "http://" + domain;
        }
        if (!domain.endsWith("/")) domain += "/";
        return domain + key;
    }

    /**
     * 上传Base64编码的音频数据到Kodo
     * @param base64Audio Base64编码的音频数据
     * @param ext 文件扩展名，如 "mp3", "wav"
     * @return 上传后的公开访问URL
     * @throws Exception 上传失败时抛出异常
     */
    public String uploadBase64Audio(String base64Audio, String ext) throws Exception {
        if (base64Audio == null || base64Audio.trim().isEmpty()) {
            throw new IllegalArgumentException("Base64 audio data cannot be null or empty");
        }
        
        // 解码Base64数据
        byte[] audioData = Base64.getDecoder().decode(base64Audio);
        
        // 使用现有的uploadBytes方法上传
        return uploadBytes(audioData, ext);
    }
}


